package com.outsider.thunder.service;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.eclipse.jetty.util.thread.Timeout.Task;

import com.jfinal.plugin.activerecord.Page;
import com.outsider.thunder.dao.TaskBase;
import com.outsider.thunder.dao.TaskUserRelation;
import com.outsider.util.Const;
import com.outsider.util.thunder.Thunder;
import com.outsider.weixin.dao.User;

public class ThunderService {
	

	public Integer addThunderTask(Object target,String openID) {

		Integer userID=User.dao.findIDbyOpenID(openID);
		int tryTime = 0;
		int beforeNum = TaskBase.dao.countThunderTask();
		System.out.println(beforeNum);
		Method method = null;
		// 判定target类型 bt Or Url
		// TODO 微信不支持上传文件
		try {
			//判断任务url是否已存在
			if (target instanceof String){
				Long taskID=TaskBase.dao.findIDbyURL((String)target);
				if (taskID==null)
				  method = this.getClass().getDeclaredMethod("doAddLinkTask", String.class);
				else{
					if (TaskUserRelation.dao.isExist(taskID, userID)) return Const.THUNDER_TASK_ADD_EXIST;
					Logger.getLogger("").info("linkTask " + (String) target + " add success");
					TaskUserRelation taskUserRelation=new TaskUserRelation();
					taskUserRelation.setTaskId(taskID);
					taskUserRelation.setUserId(userID);
					taskUserRelation.save();
					return Const.THUNDER_TASK_ADD_SUCCESS;
				}
				  
			}	
			else if (target instanceof File)
				method = this.getClass().getDeclaredMethod("doBtTask", String.class);
		} catch (NoSuchMethodException | SecurityException e) {
			e.printStackTrace();
		}
		while (tryTime <= 5) {
			try {
				method.invoke(this, (String) target);
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				e.printStackTrace();
			}
			tryTime++;
			int afterNum = TaskBase.dao.countThunderTask();
			System.out.println(beforeNum + " " + afterNum);
			if (afterNum == beforeNum)
				Thunder.getInstance().reboot();
			else {
				Logger.getLogger("").info("linkTask " + (String) target + " add success");
				TaskUserRelation taskUserRelation=new TaskUserRelation();
				taskUserRelation.setTaskId(TaskBase.dao.findLastTaskID());
				taskUserRelation.setUserId(userID);
				taskUserRelation.save();
				return Const.THUNDER_TASK_ADD_SUCCESS;
			}
		}
		return Const.THUNDER_TASK_ADD_FAIL;
	}

	private void doAddLinkTask(String url) {
		System.out.println(url);
		Thunder.getInstance().startLinkTask(url);
	}
	//TODO
	private void doBtTask(File file){
	}
	
	public List<TaskBase> findLast10Task(String openID){
		Integer userID=User.dao.findIDbyOpenID(openID);
		List<TaskUserRelation> relationList=TaskUserRelation.dao.findLast10TaskID(userID);
		List<TaskBase> result=new ArrayList<>();
		relationList.forEach(taskUserRelation->{
			System.out.println(taskUserRelation.getTaskId());
			result.add(TaskBase.dao.findById(taskUserRelation.getTaskId()));
		});
		return result;
	}
	
	public List<TaskBase> getAll(Integer userID){
		List<TaskUserRelation> relationList=TaskUserRelation.dao.findAllRealtionByUserID(userID);
		List<TaskBase> list=new ArrayList<>();
		relationList.forEach(taskUserRelation->{
			list.add(TaskBase.dao.findById(taskUserRelation.getTaskId()));
		});
		
		for (TaskBase taskBase:list)
			taskBase.setName(taskBase.getName().trim());
		return list;
	}
	
	public boolean delete(Long taskID,Integer userID){
		Integer count=TaskUserRelation.dao.countRecordByTaskID(taskID);
		//存在多个用户指向同一Task 删除relation
		if (count>1){
			return TaskUserRelation.dao.delectByUserIDAndTaskID(userID, taskID);
		}
		//只有一名用户的Task 删除relation与task
		else{
			TaskUserRelation.dao.delectByUserIDAndTaskID(userID, taskID);
			Thunder.getInstance().shutdown();
			int times=0;
			while (TaskBase.dao.deleteById(taskID)==false){
				times++;
				if (times==5) return false;
			}
			Thunder.getInstance().startUp();
			return true;
		}
	}
	
}
